// Simulating the full data flow from frontend to backend
console.log('=== SIMULATING PARAMETER DATA FLOW ===\n');

// 1. Simulate parameter data entry in frontend (as field IDs)
const fieldIdData = {
  '611': 'TEST_DESIGN_CODE_001',
  '612': 'TEST_PURCHASE_CODE_002', 
  '615': 'TEST_LOGISTICS_CODE_003'
};

console.log('1. Frontend field ID data:', fieldIdData);

// 2. Simulate localStorage storage format (from device-type-tree.tsx getTempParameterData)
const tempInstanceId = 123456;
const deviceTypeCode = 'L4-06-01-01-01-000';

const localStorageData = {
  [`${tempInstanceId}-table_c2`]: fieldIdData
};

console.log('2. localStorage format:', localStorageData);

// 3. Simulate the getTempParameterData conversion
const simulateGetTempParameterData = (instanceId) => {
  const result = {
    naming: {},
    position: {},
    base_params: {}
  };

  Object.entries(localStorageData).forEach(([key, fieldData]) => {
    console.log('Processing localStorage key:', key, fieldData);
    
    const [tempId, tableName] = key.split('-');
    if (tableName && fieldData && tempId == instanceId) {
      let tableType = '';
      if (tableName.includes('table_c2') || tableName.includes('naming')) {
        tableType = 'naming';
      } else if (tableName.includes('table_c6') || tableName.includes('position')) {
        tableType = 'position';
      } else if (tableName.includes('table_c') || tableName.includes('base_params')) {
        tableType = 'base_params';
      }

      if (tableType) {
        const convertedData = {};
        Object.entries(fieldData).forEach(([fieldId, value]) => {
          if (value && String(value).trim()) {
            convertedData[fieldId] = String(value).trim();
          }
        });
        
        if (Object.keys(convertedData).length > 0) {
          result[tableType] = convertedData;
          console.log(`Set ${tableType} data:`, convertedData);
        }
      }
    }
  });

  return result;
};

const parameterData = simulateGetTempParameterData(tempInstanceId);
console.log('3. getTempParameterData result:', parameterData);

// 4. Simulate the backend field conversion
console.log('\n4. BACKEND FIELD CONVERSION SIMULATION:');

// Field metadata (from our debug output)
const fieldMetadata = [
  { id: 611, field_name: '设计物资编码' },
  { id: 612, field_name: '采购物资编码' },
  { id: 615, field_name: '物流编码' }
];

const convertFieldIdDataToEmbeddedFields = (fieldIdData, tableName, prefix) => {
  const embeddedFields = {};
  
  Object.entries(fieldIdData).forEach(([fieldId, value]) => {
    const field = fieldMetadata.find(f => f.id === parseInt(fieldId));
    if (field && value && String(value).trim()) {
      const embeddedFieldName = `${prefix}_${field.field_name}`;
      embeddedFields[embeddedFieldName] = String(value).trim();
      console.log(`Field conversion: ID ${fieldId} -> ${embeddedFieldName} = ${value}`);
    } else {
      console.log(`Field conversion FAILED: ID ${fieldId} - field not found or empty value`);
    }
  });
  
  return embeddedFields;
};

let embeddedFields = {};

if (parameterData.naming && Object.keys(parameterData.naming).length > 0) {
  const namingFields = convertFieldIdDataToEmbeddedFields(parameterData.naming, 'table_c2', 'naming');
  embeddedFields = { ...embeddedFields, ...namingFields };
}

console.log('5. Final embedded fields for SQL insertion:', embeddedFields);

// 6. Simulate the SQL construction
console.log('\n6. SQL CONSTRUCTION SIMULATION:');
const baseFields = ['device_type_code', 'instance_number', 'object_number', 'object_description', 'pbs_level_id', 'pbs_instance_id'];
const allFields = [...baseFields, ...Object.keys(embeddedFields)];
const placeholders = allFields.map(() => '?').join(', ');

const tableName = 'device_instances_piping_centrifugal_pump';
const insertSQL = `
  INSERT INTO [${tableName}] (${allFields.map(f => `[${f}]`).join(', ')})
  VALUES (${placeholders})
`;

console.log('Generated SQL:', insertSQL);

const baseValues = [
  'L4-06-01-01-01-000', // device_type_code
  '001',                // instance_number  
  'PUMP-001',          // object_number
  'Test pump',         // object_description
  null,                // pbs_level_id
  null                 // pbs_instance_id
];
const embeddedValues = Object.values(embeddedFields);
const allValues = [...baseValues, ...embeddedValues];

console.log('SQL Values:', allValues);

console.log('\n=== FLOW ANALYSIS COMPLETE ===');
console.log('Expected outcome: 3 embedded fields should be inserted with values');
console.log('Fields that should be populated:');
Object.entries(embeddedFields).forEach(([field, value]) => {
  console.log(`  ${field}: ${value}`);
});